package authority.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import authority.entity.User;

@WebFilter(urlPatterns = "/*" )
public class AuthorityFilter implements Filter {

	private List<String> url = new ArrayList<String>();
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		url.add("/userServlet");
		url.add("/ueServlet");
		url.add("/push");
		url.add("/druid");
		url.add("/excelServlet");
		url.add("/deptServlet");
		url.add("/testServlet");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//拦截请求地址
		HttpServletRequest httpServletRequest=(HttpServletRequest) request;
		String path=httpServletRequest.getServletPath();//接收一下请求地址
		
		//针对于静态资源不做验证
		if(path.lastIndexOf(".")>0){//不针对jsp进行验证，只有是servlet的时候才验证
			chain.doFilter(request, response);
		}else{
			User user=(User) httpServletRequest.getSession().getAttribute("user");
			if(url.contains(path)||user.getPermissions().contains(path)){//通过验证
				chain.doFilter(request, response);
			}else{//不通过验证
				HttpServletResponse httpServletResponse=(HttpServletResponse) response;
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.html");
			}
		}
	}

	@Override
	public void destroy() {

	}

}
